﻿using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Health : NetworkBehaviour {
    public bool isEnemy;
    public const int maxHp = 100;
    private EnemySpawner enemySpawner;
    //public GameObject enemySpawnerGameObject;//prefab里面不能把Hierarchy里面的东西引进来...可以每一个player身上带一个创建GameObject?

    [SyncVar(hook = "updateHp")]
    public int hp = maxHp;

    private NetworkStartPosition[] spawnPositions;
    public Slider hpBar;


	// Use this for initialization
	void Start () {
        spawnPositions = FindObjectsOfType<NetworkStartPosition>();
        hpBar.value = 1.0f;
        enemySpawner = GameObject.Find("EnemySpawner").GetComponent<EnemySpawner>();
    }
	
	// Update is called once per frame
	void Update () {
	
	}

    public void Hurt(int damage)
    {
        if(isServer == false)
        {
            return;
        }
        hp -= damage;
        if(hp < 0)
        {
            hp = 0;
        }

        if(hp == 0)
        {
            hp = maxHp;
            RpcRespawn();
        }
    }

    public void updateHp(int health)
    {
        hpBar.value = health / (float)maxHp;
    }

    /// <summary>
    /// player一般客户端做，但和player无关的一般都是server做，为了同步
    /// </summary>
    [ClientRpc]//服务端调客户端，如果不加这个，服务端攻击，客户端的死亡在客户端那边看不会同步，因为服务端只有调本地player的权限，没有调别的客户端的权限，但加了这个之后就要以了
    private void RpcRespawn()
    {
        //isLocalPlayer不要忘了，这个只对player有用，对于玩家生成的别的东西都没有用
        if(isEnemy)
        {
            enemySpawner.CreateEnemy();
            Destroy(gameObject);
        }
        else
        {
            if (isLocalPlayer == false)
            {
                return;
            }
            Vector3 spawnNewPosition = Vector3.zero;
            if (spawnPositions != null && spawnPositions.Length > 0)
            {
                int index = Mathf.FloorToInt(Random.Range(0, spawnPositions.Length - 1));
                spawnNewPosition = (spawnPositions[index]).transform.position;
            }
            transform.position = spawnNewPosition;
        }
    }
}
